import sys
import subprocess
import logging
import webbrowser
import os
from pathlib import Path

logger = logging.getLogger(__name__)

class PermissionManager:
    @staticmethod
    def check_notification_permissions():
        """检查通知权限并引导用户开启"""
        platform = sys.platform
        
        if platform == 'darwin':  # macOS
            return MacOSPermissionManager.check_permissions()
        elif platform == 'win32':  # Windows
            return WindowsPermissionManager.check_permissions()
        else:
            logger.warning(f"Unsupported platform: {platform}")
            return False

class MacOSPermissionManager:
    @staticmethod
    def check_permissions():
        try:
            # 检查通知中心权限
            check_script = 'tell application "System Events" to get properties of current user'
            result = subprocess.run(
                ['osascript', '-e', check_script],
                capture_output=True,
                text=True
            )
            
            if result.returncode != 0:
                # 打开系统设置
                open_script = 'tell application "System Settings" to activate'
                subprocess.run(['osascript', '-e', open_script])
                
                # 显示引导信息
                alert_script = (
                    'display dialog "请在系统设置中允许通知权限：\\n\\n'
                    '1. 点击"通知与专注模式"\\n'
                    '2. 找到"终端"或"Python"\\n'
                    '3. 开启通知权限" '
                    'with title "通知权限设置" '
                    'buttons {"好的"} '
                    'default button 1'
                )
                subprocess.run(['osascript', '-e', alert_script])
                return False
                
            return True
            
        except Exception as e:
            logger.error(f"检查通知权限失败: {e}")
            return False

class WindowsPermissionManager:
    @staticmethod
    def check_permissions():
        try:
            # Windows 10 及以上版本检查通知权限
            if sys.getwindowsversion().major >= 10:
                # 使用 PowerShell 检查通知权限
                check_script = '''
                $app = Get-StartApps | Where-Object {$_.Name -like "*Python*"} | Select-Object -First 1
                if ($app) {
                    $path = $app.AppID
                    $settings = Get-ItemProperty -Path "HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Notifications\\Settings\\$path" -ErrorAction SilentlyContinue
                    if ($settings -and $settings.Enabled -eq 0) {
                        return $false
                    }
                }
                return $true
                '''
                result = subprocess.run(['powershell', '-Command', check_script], 
                                      capture_output=True, 
                                      text=True)
                
                if "false" in result.stdout.lower():
                    # 打开 Windows 通知设置
                    subprocess.run(['start', 'ms-settings:notifications'], shell=True)
                    
                    # 显示引导信息
                    guide_script = '''
                    Add-Type -AssemblyName System.Windows.Forms
                    [System.Windows.Forms.MessageBox]::Show(
                        "请在 Windows 设置中允许通知：`n1. 在通知设置中找到 Python/Terminal`n2. 开启通知权限`n3. 点击确定以继续",
                        "通知权限设置",
                        [System.Windows.Forms.MessageBoxButtons]::OK,
                        [System.Windows.Forms.MessageBoxIcon]::Information
                    )
                    '''
                    subprocess.run(['powershell', '-Command', guide_script])
                    return False
            return True
            
        except Exception as e:
            logger.error(f"Failed to check notification permissions: {e}")
            return False 